package cn.edu.zzuli;

/**
 * @Date: 2021/3/6 17:41
 * @Author: 绯色下午茶
 * @Description: 题目，现在两个线程，可以操作初始值为0的一个变量，
 * 实现一个线程对该变量加1，另一个线程对该变量减1
 * 实现交替，10轮
 */
class AirCondirtioner {
    private int number = 0;
    public synchronized void increment() throws InterruptedException {
        /**
         * 判断需要使用while，不能使用if
         */
        while (number!=0){
            this.wait();
        }
        number++;
        System.out.println(number+"  ***    "+Thread.currentThread().getName());

        this.notifyAll();
    }
    public synchronized void decrement() throws InterruptedException {
        while (number==0){
            this.wait();
        }
         number--;
        System.out.println(number+"  ***    "+Thread.currentThread().getName());

        this.notifyAll();
    }
}

public class ThreadWaitBotifyDemo {
    public static void main(String[] args) {
        AirCondirtioner airCondirtioner = new AirCondirtioner();

        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airCondirtioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airCondirtioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airCondirtioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                try {
                    airCondirtioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D ").start();
    }
}
